﻿using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using System.Linq;

namespace RayD.Repository.DB
{
    /// <summary>
    /// 数据访问(SqlServer)上下文
    /// </summary>
    public class DataBaseContext : DbContext
    {
        public DataBaseContext(DbContextOptions options) : base(options)
        {

        }

        /// <summary>
        /// 模型自动映射
        /// </summary>
        /// <param name="builder"></param>
        protected override void OnModelCreating(ModelBuilder builder)
        {
            //反射获取实体类程序集类
            var entityTypes = Assembly.GetExecutingAssembly().GetTypes()
            .Where(type => !string.IsNullOrWhiteSpace(type.Namespace) && type.Namespace.StartsWith("RayD.Repository.Entites"))
            .Where(type => type.GetTypeInfo().IsClass)
            .Where(type => type.GetTypeInfo().BaseType != null)
            .Where(type => type.IsDefined(typeof(TableAttribute))).ToList();
            //循环添加模型映射
            foreach (var entityType in entityTypes)
            {
                //  防止重复附加模型，否则会在生成指令中报错
                if (builder.Model.FindEntityType(entityType) != null)
                    continue;
                builder.Model.AddEntityType(entityType);
            }
            base.OnModelCreating(builder);
        }
    }
}
